package com.hilinos.base.common.init;

import com.hilinos.base.common.Constant;
import com.hilinos.base.common.config.ServerConfig;
import com.hilinos.base.service.KeyInfoService;
import com.hilinos.base.service.OrgDeptService;
import com.hilinos.base.service.OrgInfoService;
import com.hilinos.base.service.UserAccountService;
import com.hilinos.base.service.UserInfoService;
import com.hilinos.base.user.entity.pojo.KeyInfoPoJo;
import com.hilinos.base.user.entity.pojo.OrgDeptPoJo;
import com.hilinos.base.user.entity.pojo.OrgInfoPoJo;
import com.hilinos.base.user.entity.pojo.UserAccountPoJo;
import com.hilinos.base.user.entity.pojo.UserInfoPoJo;
import com.hilinos.common.util.RandomUtils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import lombok.extern.slf4j.Slf4j;

/**
 * 超管账号初始化
 * 检查超管账号，如果不存在则创建
 *
 * @author qhl
 */
@Slf4j
@Order(10002)
@Component
public class AdminInit implements ApplicationRunner {

    @Autowired
    private ServerConfig serverConfig;

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private UserAccountService userAccountService;

    @Autowired
    private KeyInfoService keyInfoService;

    @Autowired
    private OrgInfoService orgInfoService;
    @Autowired
    private OrgDeptService orgDeptService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void run(ApplicationArguments args) throws Exception {
        log("开始");

        keyInfoService.saveOrUpdate(KeyInfoPoJo.builder()
                .keyAppid(serverConfig.getAdminAppid())
                .keyType(Constant.SU_USER_TYPE_ADMIN)
                .keySecret(RandomUtils.genRandomStr(24))
                .keyStatus(1)
                .build());

        OrgInfoPoJo orgInfo = orgInfoService.detail(serverConfig.getAdminOrgId(), serverConfig.getAdminAppid());

        if (ObjectUtils.isEmpty(orgInfo)) {
            log("超管机构不存在，默认创建 orgId: {}", serverConfig.getAdminOrgId());
            orgInfoService.save(OrgInfoPoJo.builder()
                    .appid(serverConfig.getAdminAppid())
                    .orgId(serverConfig.getAdminOrgId())
                    .orgName("超管机构")
                    .build());
            log("超管机构创建成功 orgId: {}", serverConfig.getAdminOrgId());
        } else {
            log("超管机构存在 orgId: {}", serverConfig.getAdminOrgId());
        }

        OrgDeptPoJo deptInfo = orgDeptService.detail(serverConfig.getAdminDeptId(), serverConfig.getAdminOrgId(),
                serverConfig.getAdminAppid());

        if (ObjectUtils.isEmpty(deptInfo)) {
            log("超管部门不存在，默认创建 deptId: {}", serverConfig.getAdminDeptId());
            orgDeptService.save(OrgDeptPoJo.builder()
                    .appid(serverConfig.getAdminAppid())
                    .deptId(serverConfig.getAdminDeptId())
                    .orgId(serverConfig.getAdminOrgId())
                    .orgName("超管机构")
                    .build());
            log("超管部门创建成功 deptId: {}", serverConfig.getAdminDeptId());
        } else {
            log("超管部门存在 deptId: {}", serverConfig.getAdminDeptId());
        }

        UserInfoPoJo adminInfo = userInfoService.getDetail(serverConfig.getAdminUserId(), Constant.SU_USER_TYPE_ADMIN,
                serverConfig.getAdminAppid());
        if (ObjectUtils.isEmpty(adminInfo)) {
            log("超管用户不存在，默认创建 userId: {}", serverConfig.getAdminUserId());
            userInfoService.save(UserInfoPoJo.builder().userDisplayName("超级管理员").userId(serverConfig.getAdminUserId())
                    .orgId(serverConfig.getAdminOrgId()).deptId(serverConfig.getAdminDeptId())
                    .appid(serverConfig.getAdminAppid()).userTypeName("超级管理员").userType(Constant.SU_USER_TYPE_ADMIN)
                    .build());
            log("超管用户创建成功 userId: {}", serverConfig.getAdminUserId());
        } else {
            log("超管用户存在 userId: {}", serverConfig.getAdminUserId());
        }

        UserAccountPoJo adminAccountInfo = userAccountService.getDetail(serverConfig.getAdminUserId(),
                serverConfig.getDefaultAccountType(), serverConfig.getAdminOrgId(), serverConfig.getAdminAppid());
        if (ObjectUtils.isEmpty(adminAccountInfo)) {
            log("超管账号不存在，默认创建 accountId: {} accountType: {} password: 123456", serverConfig.getAdminAccountId(),
                    serverConfig.getDefaultAccountType());
            adminAccountInfo = UserAccountPoJo.builder().userId(serverConfig.getAdminUserId())
                    .appid(serverConfig.getAdminAppid()).orgId(serverConfig.getAdminOrgId())
                    .accountId(serverConfig.getAdminAccountId()).accountType(serverConfig.getDefaultAccountType())
                    .accountSecretExtra(RandomUtils.genRandomStr()).build();
            adminAccountInfo.setAccountSecret(
                    adminAccountInfo.genPasswordByClearText("123456", adminAccountInfo.getAccountSecretExtra()));
            userAccountService.save(adminAccountInfo);
            log("超管账号创建成功 accountId: {} accountType: {} password: 123456", serverConfig.getAdminAccountId());
        } else {
            log("超管账号存在 accountId: {} accountType: {}", serverConfig.getAdminAccountId(),
                    serverConfig.getDefaultAccountType());

        }
    }

    private void log(String msg, Object... args) {
        log.info("【启动检测】 " + msg, args);
    }
}
